<?php

namespace CHOMP\SGIBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use CHOMP\SGIBundle\Entity\Usuario;
use CHOMP\SGIBundle\Form\UsuarioType;
use Pagerfanta\Pagerfanta;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use CHOMP\SGIBundle\Services\SessionManager;
use JMS\DiExtraBundle\Annotation as DI;
use Symfony\Component\HttpFoundation\Session\Session;

/**
 * Usuario controller.
 *
 * @Route("/usuario")
 */
class UsuarioController extends Controller
{
	/**
	 * 
	 * @var SessionManager
	 * @DI\Inject("session.manager")
	 */
	public $sessionSvc;

    /**
     * Lists all Usuario entities.
     *
     * @Route("/", name="usuario")
     * @Method("GET")
     * @Template()
     */
    public function listarAction(Request $request, $page)
    {
  		if ($this->sessionSvc->userIsLogged()){
			$us = $this->sessionSvc->getCurrentUser();
			if($us->getRol()->getNombre()=='Administrador'){
	
				$workflows = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Workflow')->getByEmmpresa($this->sessionSvc->getSession('empresa'));
				$cuentaAnalitica = $this->getDoctrine()->getRepository('CHOMPSGIBundle:CuentaAnalitica')->getByEmmpresa($this->sessionSvc->getSession('empresa'));
				$grupoSoporte = $this->getDoctrine()->getRepository('CHOMPSGIBundle:GrupoSoporte')->getByEmmpresa($this->sessionSvc->getSession('empresa'));
				
				if(count($grupoSoporte)<1){
					$this->sessionSvc->addFlash('msgWarn','Bienvenido! Debe dar de alta al menos un Grupo de Soporte.');				
					return $this->redirect($this->generateUrl('gruposoporte_nuevo'));
				}
				if(count($cuentaAnalitica)<1){
					$this->sessionSvc->addFlash('msgWarn','Bienvenido! Debe dar de alta al menos una Cuenta Analitica.');				
					return $this->redirect($this->generateUrl('cuentaAnalitica_nuevo'));
				}
				if(count($workflows)<1){
					$this->sessionSvc->addFlash('msgWarn','Bienvenido! Debe dar de alta al menos un Workflow.');				
					return $this->redirect($this->generateUrl('workflow_nuevo'));			
				}
			}		

			$em = $this->getDoctrine()->getManager();
			$session = $request->getSession();
			
			$this->sessionSvc->getLdapUsers();

			if($session->get('esAdmin')=='NO'){
				$query = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Usuario')->getAllActivasPorEmpresa($session->get('empresa'));		
			}else{
				$query = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Usuario')->getAll();		
			}	
				
			$paginador = new Pagerfanta(new DoctrineORMAdapter($query));
			$paginador->setMaxPerPage(10);
			$paginador->setCurrentPage($page); 
			
			return $this->render('CHOMPSGIBundle:Usuario:listar.html.twig', array('usuarios' => $paginador));		
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}		
    }
    /**
     * Creates a new Usuario entity.
     *
     * @Route("/", name="usuario_create")
     * @Method("POST")
     * @Template("CHOMPSGIBundle:Usuario:nuevo.html.twig")
     */
    public function createAction(Request $request)
    {
        $session = $request->getSession();
        
        $entity = new Usuario();
		
        $form = $this->createCreateForm($entity, $session->get('empresa'), $session->get('esAdmin'));
        $form->handleRequest($request);

        if ($form->isValid()) {
			
            $em = $this->getDoctrine()->getManager();
			
			if($session->get('esAdmin')=='SI'){
		        $rolId = $em->getRepository('CHOMPSGIBundle:Rol')->rolByAdmin($entity->getEmpresa()->getId(), $entity->getRol()->getNombre());
				foreach($rolId as $id){
					$rol = $em->getRepository('CHOMPSGIBundle:Rol')->find($id);
				}
				$entity->setRol($rol);
			}
			
			$str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
			$cad = "";
			for($i=0;$i<12;$i++) {
				$cad .= substr($str,rand(0,62),1);
			}

			$psw = $cad;
			$encrypted = encrypt( $psw );
			$con = $entity->getLogin() .'///'. $encrypted;
			$entity->setPassword($con);

			$em->persist($entity);
			$em->flush();

			
			$message = \Swift_Message::newInstance()
			->setSubject('Bienvenido a SGI!')
			->setFrom('sgicaece@gmail.com')
			->setTo($entity->getEmail())
			->setBody( 'Bienvenido '.$entity->getLogin().'! Su clave para ingresar al sistema es "'.$psw.'", ante cualquier duda o consulta, comuníquese con su administrador. Web: www.sgicaece.com.ar');
						
			$this->get('mailer')->send($message);
			
            return $this->redirect($this->generateUrl('usuario_ver', array('id' => $entity->getId())));
        }
				
        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
    * Creates a form to create a Usuario entity.
    *
    * @param Usuario $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createCreateForm(Usuario $entity, $empId, $esAdmin)
    {
        
        $form = $this->createForm(new UsuarioType($empId, $esAdmin), $entity, array(
            'action' => $this->generateUrl('usuario_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Guardar', 'attr'=> array('class'=>'btn middle-first')));

        return $form;
    }

    /**
     * Displays a form to create a new Usuario entity.
     *
     * @Route("/new", name="usuario_nuevo")
     * @Method("GET")
     * @Template()
     */
    public function nuevoAction(Request $request)
    {
  		if ($this->sessionSvc->userIsLogged()){
			$session = $request->getSession();
			$entity = new Usuario();
			$entity->setBorrado(false);
			
			$form = $this->createCreateForm($entity, $session->get('empresa'), $session->get('esAdmin'));
	
			return array(
				'entity' => $entity,
				'form'   => $form->createView(),
			);
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}		
    }

    /**
     * Finds and displays a Usuario entity.
     *
     * @Route("/{id}", name="usuario_ver")
     * @Method("GET")
     * @Template()
     */
    public function verAction($id)
    {
  		if ($this->sessionSvc->userIsLogged()){
			$em = $this->getDoctrine()->getManager();
	
			$entity = $em->getRepository('CHOMPSGIBundle:Usuario')->find($id);
	
			if (!$entity) {
				throw $this->createNotFoundException('Unable to find Usuario entity.');
			}
			
			switch ($entity->getEstado()) {
				case 0:
					$entity->setEstado('Activo');
				break;
				case 1:
					$entity->setEstado('Inactivo');
				break;
				case 2:
					$entity->setEstado('Lockeado');
				break;
				case 3:
					$entity->setEstado('Borrado');
				break;
				case 4:
					$entity->setEstado('Expirado');
				break;
			}
			
			return array(
				'entity'      => $entity,
			);
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}		
    }

    /**
     * Displays a form to editar an existing Usuario entity.
     *
     * @Route("/{id}/edit", name="usuario_editar")
     * @Method("GET")
     * @Template()
     */
    public function editarAction(Request $request, $id)
    {
  		if ($this->sessionSvc->userIsLogged()){
			$session = $request->getSession();
			$em = $this->getDoctrine()->getManager();
	
			$entity = $em->getRepository('CHOMPSGIBundle:Usuario')->find($id);
			
			if (!$entity) {
				throw $this->createNotFoundException('Unable to find Usuario entity.');
			}
	
			$editForm = $this->createEditForm($entity, $session->get('esAdmin'));
	
			return array(
				'entity'      => $entity,
				'edit_form'   => $editForm->createView(),
			);
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}		
    }

    /**
    * Creates a form to edit a Usuario entity.
    *
    * @param Usuario $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Usuario $entity, $esAdmin)
    {
		$usuario = $this->sessionSvc->getCurrentUser();
	    $form = $this->createForm(new UsuarioType($usuario->getEmpresa()->getId(), $esAdmin), $entity, array(
            'action' => $this->generateUrl('usuario_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Guardar', 'attr'=> array('class'=>'btn middle-first')));

        return $form;
    }
    /**
     * Edits an existing Usuario entity.
     *
     * @Route("/{id}", name="usuario_update")
     * @Method("PUT")
     * @Template("CHOMPSGIBundle:Usuario:editar.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
		$session = $request->getSession();
        $entity = $em->getRepository('CHOMPSGIBundle:Usuario')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Usuario entity.');
        }

        $editForm = $this->createEditForm($entity, $session->get('esAdmin'));
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
			if($session->get('esAdmin')=='SI'){
				$rolId = $em->getRepository('CHOMPSGIBundle:Rol')->rolByAdmin($entity->getEmpresa()->getId(), $entity->getRol()->getNombre());	
				foreach($rolId as $id){
					$rol = $em->getRepository('CHOMPSGIBundle:Rol')->find($id);
				}
				$entity->setRol($rol);
			}

			$em->flush();
			
            return $this->redirect($this->generateUrl('usuario_listar'));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
        );
    }
    /**
     * Deletes a Usuario entity.
     *
     * @Route("/{id}", name="usuario_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('CHOMPSGIBundle:Usuario')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Usuario entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('usuario_listar'));
    }

	public function borrarAction($id) {
  		if ($this->sessionSvc->userIsLogged()){
			
			$em = $this->getDoctrine()->getManager();
			$idsArray = explode (',', $id);
	
			for ($i = 0; $i < count($idsArray); $i++){
				$usABorrar = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Usuario')->find($idsArray[$i]);
				$usABorrar->setBorrado(1);
				$em->persist($usABorrar);
			}
	
			$em->flush();
					
			return $this->redirect($this->generateUrl('usuario_listar'));	
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}		
	}

	public function activarAction($id) {
  		if ($this->sessionSvc->userIsLogged()){
			
			$em = $this->getDoctrine()->getManager();
			$usuario = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Usuario')->find($id);;
			$usuario->setBorrado(0);
			$em->persist($usuario);
	
			$em->flush();
					
			return $this->redirect($this->generateUrl('usuario_listar'));	
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}		
	}

	public function filtrarAction(Request $request, $page)
	{
  		if ($this->sessionSvc->userIsLogged()){
			$nombre = $request->get('nombreUsuario');
			if($this->sessionSvc->getSession('esAdmin') == 'SI'){
				$query = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Usuario')->getFiltradoAdmin($nombre);
			}else{
				$query = $this->getDoctrine()->getRepository('CHOMPSGIBundle:Usuario')->getFiltrado($nombre, $this->sessionSvc->getSession('empresa'));			
			}
			$paginador = new Pagerfanta(new DoctrineORMAdapter($query));
			$paginador->setMaxPerPage(10);
			$paginador->setCurrentPage($page); 
		
			return $this->render('CHOMPSGIBundle:Usuario:listar.html.twig', array('usuarios' => $paginador));
		}else{
			return $this->redirect($this->generateUrl('chompsgi_homepage'));	
		}		
	}	
	
}

function encrypt( $q ) {
	$cryptKey = 'qJB0rGtIn5UB1xG03efyCp';
	$qEncoded = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), $q, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );
	return( $qEncoded );
}